"use client";

import { LuckyWheelPage } from "@/app/pages/lucky/lucky-wheel-page";
import { LuckyGridPage } from "@/app/pages/lucky/lucky-grid-page";
import dynamic from "next/dynamic";
import { useEffect, useState } from "react";
import './globals.css';
const Cookies = require('js-cookie');

const StrategyArmoryButton = dynamic(() => import("./components/StrategyArmory").then(mod => mod.StrategyArmory));
const StrategyRuleWeightButton = dynamic(() => import("./components/StrategyRuleWeight").then(mod => mod.StrategyRuleWeight));
const MemberCardButton = dynamic(() => import("./components/MemberCard").then(mod => mod.MemberCard));
const AwardRecord = dynamic(() => import("./components/AwardRecord").then(mod => mod.AwardRecord));
const SkuProductButton = dynamic(() => import("./components/SkuProduct").then(mod => mod.SkuProduct));
const LoginPage = dynamic(() => import("./components/login").then(mod => mod.LoginPage));

const SESSION_KEY = 'isLoggedIn';
const EXPIRATION_KEY = 'loginExpiration';

export default function Home() {
    const [isLoggedIn, setIsLoggedIn] = useState(() => {
        const savedLoginStatus = Cookies.get(SESSION_KEY);
        const expiration =  Cookies.get(EXPIRATION_KEY);

        if (savedLoginStatus && expiration && new Date().getTime() < parseInt(expiration, 10)) {
            return JSON.parse(savedLoginStatus);
        }
        return false;
    });

    const [refresh, setRefresh] = useState(0);
    const handleLoginSuccess = () => {
        const expiration = new Date().getTime() + 60 * 1000 * 15  ; // 15分钟
        Cookies.set(SESSION_KEY, JSON.stringify(true));
        Cookies.set(EXPIRATION_KEY, expiration.toString());
        setIsLoggedIn(true);
        // 跳转到特定的 URL
        var userId =  Cookies.get("userId");
        window.location.href = '/?userId='+ userId +'&activityId=100301';
    };

    const handleRefresh = () => {
        setRefresh(refresh + 1);
    };


    useEffect(() => {

        const Cookies = require('js-cookie');

        // 创建 URL 对象来解析当前 URL
        const currentUrl = new URL(window.location.href);
        const queryParams = new URLSearchParams(currentUrl.search);

        // 获取 URL 中的 userId 和 activityId 查询参数
        const currentUserId = queryParams.get('userId');
        const currentActivityId = queryParams.get('activityId');
        if (currentUserId != null && currentActivityId != null){
            setCookie('userId', currentUserId, 30);
            return ;
            window.location.href = '/?userId='+currentUserId+'&activityId='+currentActivityId;
        }


        const userId = Cookies.get('userId');

        const savedLoginStatus = Cookies.get(SESSION_KEY);
        const expiration = Cookies.get(EXPIRATION_KEY);

        if ( savedLoginStatus && expiration && new Date().getTime() < parseInt(expiration, 10)) {
            setIsLoggedIn(JSON.parse(savedLoginStatus));

            // 检查当前 URL 是否已经符合预期
            const currentUrl = window.location.href;
            const targetUrl = `/?userId=${userId}&activityId=100301`;

            if (!currentUrl.includes(targetUrl)) {
                // 跳转
                window.location.href = targetUrl;
            }
        } else {
            setIsLoggedIn(false);
        }
    }, []);

    const setCookie = (name: string, value: any, days: number) => {
        const date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        const expires = "expires=" + date.toUTCString();
        document.cookie = `${name}=${value};${expires};path=/`;
    };
    return (
        <div className="flex flex-col items-center justify-center min-h-screen bg-[#e7305e]">
            {!isLoggedIn ? (
                <LoginPage onLoginSuccess={handleLoginSuccess} />
            ) : (
                <>
                    <div className="flex flex-col items-center justify-center min-h-screen bg-[#e7305e]"
                         style={{ backgroundImage: "url('/background.svg')" }}>
                        <header className="text-7xl font-bold text-center text-gray-800 my-8" style={{color: "white"}}>
                            大营销抽奖平台
                        </header>
                        <div className="container">
                            {/* 会员卡 */}
                            <MemberCardButton allRefresh={refresh}/>
                            <AwardRecord allRefresh={refresh}/>
                        </div>

                        {/* 装配抽奖 */}
                        <StrategyArmoryButton/>

                        {/* 商品 */}
                        <SkuProductButton handleRefresh={handleRefresh}/>

                        {/* 中间的两个div元素 */}
                        <div className="flex flex-col md:flex-row gap-4 mb-8">
                            <div className="w-full md:w-1/2 p-6 bg-white shadow-lg rounded-lg">
                                <div className="text-gray-700">
                                    <LuckyWheelPage handleRefresh={handleRefresh}/>
                                </div>
                            </div>
                            <div className="w-full md:w-1/2 p-6 bg-white shadow-lg rounded-lg">
                                <div className="text-gray-700">
                                    <LuckyGridPage handleRefresh={handleRefresh}/>
                                </div>
                            </div>
                        </div>

                        <div className="flex items-center space-x-4">
                            <StrategyRuleWeightButton refresh={refresh}/>
                        </div>

                        {/* 底部 */}
                        <footer className="text-gray-600 text-center my-8" style={{color: "white"}}>
                        </footer>
                    </div>
                </>
            )}
        </div>
    );
}